<template>
  <div class="flv-player">
    <video class="player-video" ref="player" muted autoplay @canplay="onCanplay"></video>
  </div>
</template>
<script>
import FlvExtend from '@/utils/flvExtend.js'
export default {
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      id: `${Date.now()}`,
      player: null,
      flvInstance: null,
      isMounted: false
    }
  },
  watch: {
    url: {
      handler(val) {
        if (val && this.isMounted) {
          this.play()
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.isMounted = true
    if (!this.flvInstance && this.url) {
      this.play()
    }
  },
  beforeUnmount() {
    if (this.flvInstance) {
      this.flvInstance.destroy()
    }
  },
  methods: {
    play() {
      if (!this.url) {
        return
      }
      if (!/^rtsp:\/\/\S+/.test(this.url)) {
        this.$refs.player.src = this.url
        this.$refs.player.controls = true
        return
      }
      if (this.flvInstance) {
        this.flvInstance.destroy()
      }
      let wsUrl = location.origin.replace('http', 'ws')
      // let wsUrl = 'ws://cpu001.revai.cn:8888'
      const websocketUrl = `${wsUrl}/rtsp/${this.id}/?url=${encodeURIComponent(
        decodeURIComponent(this.url)
      )}`
      this.playRtsp(websocketUrl)
    },
    playRtsp(url) {
      // 配置需要的功能
      const flv = new FlvExtend({
        element: this.$refs.player, // *必传
        frameTracking: true, // 开启追帧设置
        updateOnStart: true, // 点击播放后更新视频
        updateOnFocus: true, // 获得焦点后更新视频
        reconnect: true, // 开启断流重连
        reconnectInterval: 0 // 断流重连间隔
      })
      this.flvInstance = flv

      // 调用 init 方法初始化视频
      // init 方法的参数与 flvjs.createPlayer 相同，并返回 flvjs.player 实例
      this.player = flv.init(
        {
          type: 'flv',
          url,
          isLive: true
        },
        {
          enableStashBuffer: false, // 如果您需要实时（最小延迟）来进行实时流播放，则设置为false
          autoCleanupSourceBuffer: true, // 对SourceBuffer进行自动清理
          stashInitialSize: 128 // 减少首帧显示等待时长
        }
      )
      // 直接调用play即可播放
      this.player.play()
    },
    onCanplay() {
      this.$emit('load')
    }
  }
}
</script>
<style lang="less" scoped>
.flv-player {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .player-video {
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
  }
}
</style>
